package com.wzx.boot.core;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ScopeMetadata;
import org.springframework.context.annotation.ScopeMetadataResolver;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class ServerApplication {


    private List<String> scanPack = new ArrayList<>();
    /**
     * 主要启动类
     */
    private Class mainClass;

    public ServerApplication(Class<?> sources) {
        this.mainClass = getMainClass();


        // 准备扫描包
        scanPack.addAll(getComponentPackage(sources));
        if (scanPack.isEmpty()) {
            scanPack.add(mainClass.getPackage().getName());
        }
    }

    private Collection<String> getComponentPackage(Class<?> sources) {
        List<String> list = new ArrayList<>();
        Annotation[] annotations = AnnotationUtils.getAnnotations(sources);
        for (Annotation annotation : annotations) {
            if (annotation instanceof ComponentScan) {
                list.addAll(Arrays.asList(((ComponentScan) annotation).basePackages()));
            }
        }
        return list;
    }

    public Class getMainClass() {
        RuntimeException ex = new RuntimeException("not found main class ");
        StackTraceElement[] list = ex.getStackTrace();
        try {
            for (StackTraceElement item : list) {
                if (item.getMethodName().equals("main")) {
                    return Class.forName(item.getClassName());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw ex;
    }

    public static void run(Class<?> sources, String[] args) {
        new ServerApplication(sources).run(args);
    }

    private void run(String[] args) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.scan(scanPack.toArray(new String[0]));
        context.refresh();
    }
}
